package com.lxl.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

public class FormatFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "route";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        HttpServletResponse response = ctx.getResponse();

        try {
            request.setCharacterEncoding("utf-8");
            String type = request.getParameter("type");
            if ( type != null && "xml".equals(type)){
                response.setContentType("text/xml;charset=utf-8");
            } else {
                response.setContentType("text/json;charset=utf-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ctx.setSendZuulResponse(true);
        return null;
    }
}
